package com.tarena.lbs.basic.web.repository;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tarena.lbs.basic.web.mapper.StoreMapper;
import com.tarena.lbs.pojo.basic.entity.StoreSearchEntity;
import com.tarena.lbs.pojo.basic.param.UserLocationParam;
import com.tarena.lbs.pojo.basic.po.StorePO;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.index.query.GeoDistanceQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Repository
public class StoreRepository extends ServiceImpl<StoreMapper, StorePO> {
    @Autowired
    private StoreMapper storeMapper;
    @Autowired
    private StoreESRepository storeESRepository;
    @Autowired
    private RestHighLevelClient restHighLevelClient;
    public void saveData(StorePO poParam) {
        //将po封装完整数据写入到持久层
        storeMapper.insert(poParam);
        //写入到ES
        StoreSearchEntity entity=new StoreSearchEntity();
        //id location storeName businessId
        BeanUtils.copyProperties(poParam,entity);
        entity.setLocation(poParam.getStoreLatitude()+","+poParam.getStoreLongitude());
        storeESRepository.save(entity);
    }

    public List<StoreSearchEntity> getNearStores(UserLocationParam param) {
        //1.准备一个搜索查询对象
        SearchRequest request=new SearchRequest("lbs_store");
        SearchSourceBuilder builder=new SearchSourceBuilder();
        //2.封装条件 只需要前5个
        builder.size(5);
        GeoDistanceQueryBuilder query = QueryBuilders.geoDistanceQuery("location");
        query.point(Double.valueOf(param.getLatitude()),Double.valueOf(param.getLongitude()));
        query.distance(100l, DistanceUnit.KILOMETERS);
        //3.发起请求
        List<StoreSearchEntity> entities=null;
        try{
            SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
            SearchHit[] hits = response.getHits().getHits();
            if (hits!=null&& hits.length>0){
             entities= Arrays.stream(hits).map(hit->{
                 return JSON.parseObject(hit.getSourceAsString(), StoreSearchEntity.class);
             }).collect(Collectors.toList());
            }
        }catch (Exception e){
            log.error("搜索定位店铺失败",e);
        }
        return entities;
    }
}
